﻿using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.SystemUI;
using System;

namespace Swsk33.SimpleArcEngine.Util
{
	/// <summary>
	/// 把绘制区域多边形内栅格值变成0
	/// </summary>
	public class SelectToZero : ICommand, ITool
	{
		/// <summary>
		/// 被操作地图对象
		/// </summary>
		private AxMapControl map;

		public void OnCreate(object Hook)
		{
			map = (AxMapControl)Hook;
		}

		public bool Enabled
		{
			get
			{
				return true;
			}
		}

		public bool Checked
		{
			get
			{
				return true;
			}
		}

		public string Name
		{
			get;
			set;
		}

		public string Caption
		{
			get;
			set;
		}

		public string Tooltip
		{
			get;
			set;
		}

		public string Message
		{
			get;
			set;
		}

		public string HelpFile
		{
			get;
			set;
		}

		public int HelpContextID
		{
			get;
			set;
		}

		public int Bitmap
		{
			get;
			set;
		}

		public string Category
		{
			get;
			set;
		}

		public void OnClick()
		{

		}

		public void OnMouseDown(int button, int shift, int x, int y)
		{
			// 获取在地图上画的矩形框
			IEnvelope rectangle = map.TrackRectangle();
			IPoint upperLeft = rectangle.UpperLeft;
			IPoint lowerRight = rectangle.LowerRight;
			IRasterLayer rasterLayer = (IRasterLayer)map.get_Layer(0);
			IRaster raster = rasterLayer.Raster;
			int colTL = 0;
			int rowTL = 0;
			((IRaster2)raster).MapToPixel(upperLeft.X, upperLeft.Y, out colTL, out rowTL);
			int colLR = 0;
			int rowLR = 0;
			((IRaster2)raster).MapToPixel(lowerRight.X, lowerRight.Y, out colLR, out rowLR);
			IPnt pnt = new PntClass();
			int iw = colLR - colTL + 1;
			int ih = rowLR - rowTL + 1;
			pnt.SetCoords(iw, ih);
			IPixelBlock pixelBlock = raster.CreatePixelBlock(pnt);
			pnt.SetCoords(colTL, rowTL);
			raster.Read(pnt, pixelBlock);
			Array array = (Array)pixelBlock.get_SafeArray(0);
			for (int i = 0; i < iw; i++)
			{
				for (int j = 0; j < ih; j++)
				{
					array.SetValue(0, i, j);
				}
			}
			pixelBlock.set_SafeArray(0, array);
			IRasterEdit edit = (IRasterEdit)raster;
			pnt.SetCoords(colTL, colLR);
			edit.Write(pnt, pixelBlock);
			edit.Refresh();
			map.Refresh();
		}

		public void OnMouseMove(int button, int shift, int x, int y)
		{

		}

		public void OnMouseUp(int button, int shift, int x, int y)
		{

		}

		public void OnDblClick()
		{

		}

		public void OnKeyDown(int keyCode, int shift)
		{

		}

		public void OnKeyUp(int keyCode, int shift)
		{

		}

		public bool OnContextMenu(int x, int y)
		{
			return true;
		}

		public void Refresh(int hdc)
		{

		}

		public bool Deactivate()
		{
			return true;
		}

		public int Cursor
		{
			get;
			set;
		}
	}
}